package com.crowntit.controller;

import com.crowntit.service.ILoginService;
import com.crowntit.common.Constants;
import com.crowntit.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@RestController
@CrossOrigin("*")
@RequestMapping("/api/v1/login/")
public class LoginController {

    @Resource
    private ILoginService loginService;

    /**
     * 用户登录的接口，用于申请二维码ticket
     * @return 二维码的ticket
     */
    @RequestMapping(value = "weixin_qrcode_ticket", method = RequestMethod.GET)
    public Response<String> weixinQrCodeTicket(){
        try {
            String ticket = loginService.createQrCode();
            log.info("生成微信扫码登录 ticket:{}", ticket);
            return Response.<String>builder()
                    .code(Constants.ResponseCode.SUCCESS.getCode())
                    .message(Constants.ResponseCode.SUCCESS.getInfo())
                    .data(ticket).build();
        } catch (IOException e) {
            log.error("生成微信扫码登录 ticket 失败", e);
            return Response.<String>builder()
                    .code(Constants.ResponseCode.ERROR.getCode())
                    .message(Constants.ResponseCode.ERROR.getInfo())
                    .build();
        }
    }

    @RequestMapping(value = "check_login", method = RequestMethod.GET)
    public Response<String> checkLogin(@RequestParam String ticket){
        try {
            String openidToken = loginService.checkLogin(ticket);
            log.info("扫描检测登录结果 ticket:{} openidToken:{}", ticket, openidToken);

            if (StringUtils.isNotBlank(openidToken)){
                return Response.<String>builder()
                        .message(Constants.ResponseCode.SUCCESS.getInfo())
                        .code(Constants.ResponseCode.SUCCESS.getCode())
                        .data(openidToken)
                        .build();
            } else {
                return Response.<String>builder()
                        .code(Constants.ResponseCode.NO_LOGIN.getCode())
                        .message(Constants.ResponseCode.NO_LOGIN.getInfo())
                        .build();
            }
        } catch (Exception e){
            log.info("扫描检测登录结果失败 ticket:{}", ticket);
            return Response.<String>builder()
                    .code(Constants.ResponseCode.ERROR.getCode())
                    .message(Constants.ResponseCode.ERROR.getInfo())
                    .build();
        }
    }
}
